<template>
	<view>
		<u-navbar :border-bottom="false" title="添加地址" :title-size="36" :title-bold="true" :title-color="textColor">
		</u-navbar>
		<u-form class="container" :model="form" ref="addressForm" :error-type="['toast']">
			<u-form-item label-position="top" required label="姓名" :label-style="labelStyle" prop="name">
				<u-input v-model="form.name" placeholder="请输入收货人姓名" />
			</u-form-item>
			<u-form-item label-position="top" required label="手机号" :label-style="labelStyle" prop="phoneNumber">
				<u-input v-model="form.phoneNumber" placeholder="请输入手机号" />
			</u-form-item>
			<u-form-item label-position="top" required label="地址信息" :label-style="labelStyle" prop="regionId">
				<u-input type="select" :select-open="pickerShow" v-model="region" placeholder="省/市/区（县）" @click="pickerShow = true" />
				
			</u-form-item>
			<u-form-item label-position="top" required label="详细地址" :label-style="labelStyle" prop="address" >
				<u-input v-model="form.address" placeholder="请输入详细地址" />
				<image src="/static/home/dingwei.png" style="width: 30rpx;height:36rpx;" mode="" @click="chooseLocation"></image>
			</u-form-item>
		</u-form>
		<set-submit-bt text="保 存" @click="handleSubmit" />
		<akLoading isFullScreen :active="loading"></akLoading>
		<!-- 地区选择 -->
		<u-picker mode="region" v-model="pickerShow" :area-code="areaCode" :confirm-color="themeColor" @confirm="regionConfirm"></u-picker>
	</view>
</template>

<script>
	import SetSubmitBt from '@/components/set-submit-bt/index.vue'
	import { useShopStore } from '@/store/shop.js';
	import { mapState } from 'pinia';
	export default {
		components: { SetSubmitBt },
		data() {
			return {
				form: {
					shopId: '',
					name: '',
					phoneNumber: '',
					regionId: '',
					address: ''
				},
				loading:false,
				rules: {
					name: [{ required: true, message: '请输入收货人姓名', trigger: ['blur'] }],
					phoneNumber: [
						{ required: true, message: '请输入手机号', trigger: ['blur'] },
						{
							validator: (rule, value, callback) => {
								return this.$u.test.mobile(value);
							},
							message: '手机号码不正确',
							trigger: ['blur'],
						}
					],
					address: [{ required: true, message: '请输入详细地址', trigger: ['blur'] }]
				},
				region: '',
				areaCode: [],
				addOrEdit: 1,
				pickerShow: false,
				labelStyle: {
					fontSize: '30rpx',
				},
				shopId:''
			}
		},
		onLoad(options) {
			this.shopId = options.shopId;
			this.form.shopId = options.shopId;
			// 获取店铺地址信息
			this.getShopAddressInfo()
		},
		computed:{
			...mapState(useShopStore, ['updateInfo'])
		},
		onReady() {
			this.$refs.addressForm.setRules(this.rules);
		},
		methods: {
			async getShopAddressInfo() {
				this.loading = true;
				const res = await this.$setHttp.get('api/Shop/GetDeliveryAddressById', {header:{shopId:this.shopId}, params: { ShopId: this.shopId } });
				this.loading = false;
				if (!res.data) return
				// 修改
				this.addOrEdit = 2
				// form赋值
				// Object.keys(this.form).forEach(key=>{
				// 	 this.form[key] = res[0][key]
				// })
				this.form = res.data[0]
				this.region = await this.getRegionName(this.form.regionId)
				let regionCode = this.form.regionId.toString()
				this.areaCode = [Number(regionCode.substr(0, 2)), Number(regionCode.substr(0, 4)), Number(regionCode)]
			},
			// 根据地址id获取省市区
			async getRegionName(id) {
				const res = await this.$setHttp.get('api/Region/GetNames', { header:{shopId:this.shopId}, params: { id } })
				return res.data
			},
			// 选择地区回调
			regionConfirm(e) {
				this.region = e.province.label + e.city.label + e.area.label;
				this.form.regionId = e.area.value;
			},
			// 定位
			chooseLocation() {
				uni.chooseLocation({
					success: async (res) => {
						console.log(res);
						this.form.address = res.address
						const result = await this.$setHttp.get('api/Shop/GetLocationByLngLat', { header:{shopId:this.shopId}, params: { latitude: res.latitude, longitude: res.longitude }})
						this.areaCode = [result.data.provinceId, result.data.cityId, result.data.regionId]
						this.region = result.data.address
						this.form.regionId = result.data.regionId
					},
					fail:(err)=>{
						console.log(err);
					}
					
				});
			},
			async handleSubmit() {
				// console.log(this.form)
				if (!this.form.regionId) return this.$u.toast('请选择所属地区')
				this.$refs.addressForm.validate(async (valid) => {
					if (!valid) return
					// 1 新增 2修改
					if (this.addOrEdit == 1) {
						const res = await this.$setHttp.post('api/Shop/AddDeliveryAddress', this.form,{ header:{shopId:this.shopId}})
						if (!res.data) return
						const address = { deliveryAddresses: [this.form] }
						this.updateInfo(address)
						this.$u.toast('添加成功', 1000, 'success')
					} else {
						const res = await this.$setHttp.post('api/Shop/UpdateDeliveryAddress', this.form,{ header:{shopId:this.shopId}})
						const address = { deliveryAddresses: [this.form] } 
						this.updateInfo(address)
						this.$u.toast('修改成功', 1000, 'success')
						
					}
					this.$mHelper.delayedJump()
				})
			}
		}
	}
</script>

<style>
	page {
		background-color: #FFFFFF;
	}
</style>

<style lang="scss" scoped>
	.container {
		padding: 0rpx 70rpx;
	}
	.profile-footer {
		position: fixed;
		z-index: 999;
		width: 100%;
		background-color: #FFFFFF;
		bottom: 0;
		padding: 0 70rpx;
	}
</style>
